package test.lucene.pinyin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;

public class App {
	
	public static void index() {
		HttpSolrClient client = new HttpSolrClient("http://localhost:8080/solr");
//		SolrInputDocument doc = new SolrInputDocument();
//		doc.addField("id", "1");
//		doc.addField("text", "今天是个好日子");
//		
//		SolrInputDocument doc2 = new SolrInputDocument();
//		doc2.addField("id", "2");
//		doc2.addField("text", "今天天气真好");
		
		SolrInputDocument doc3 = new SolrInputDocument();
		doc3.addField("id", "4");
		doc3.addField("text", "我们今天去哪吃饭呢？");
		
		List<SolrInputDocument> docs = new ArrayList<>();
//		docs.add(doc);
//		docs.add(doc2);
		docs.add(doc3);
		
		try {
			client.add("core3", docs);
			client.commit("core3");
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void query() {
		HttpSolrClient client = new HttpSolrClient("http://localhost:8080/solr");
		SolrQuery query = new SolrQuery();
		query.setQuery("text:jintian*");
		try {
			QueryResponse qr = client.query("core3", query);
			System.out.println(qr);
		} catch (SolrServerException | IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void deleteAll() {
		HttpSolrClient client = new HttpSolrClient("http://localhost:8080/solr");
		try {
			client.deleteByQuery("core3", "*:*");
		} catch (SolrServerException | IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
//		deleteAll();
		index();
		query();
	}
	
}
